<?php
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;

require_once('ActivityBase.class.php');

/**
 * +------------------------------------------------------------------------------
 * 活动模型
 * +------------------------------------------------------------------------------
 * @property int $id
 * @property string $name
 * @property string $link
 * @property string $guide
 * @property string $auto_reply_keyword
 * @property string $nickname_x
 * @property string $nickname_y
 * @property string $nickname_h
 * @property string $nickname_w
 * @property string $qrcode_x
 * @property string $qrcode_y
 * @property string $qrcode_h
 * @property string $qrcode_w
 * @property string $avatar_x
 * @property string $avatar_y
 * @property string $avatar_h
 * @property string $avatar_w
 * @property string $poster_params
 * @property string $backgroud_path
 * @property string $app_id
 * @property string $app_secret
 * @property int $start_date
 * @property int $end_date
 * @property integer $award_type
 * @property integer $award_first_min
 * @property integer $award_first_max
 * @property integer $award_two_min
 * @property integer $award_two_max
 * @property integer $award_one_min
 * @property integer $award_one_max
 * @property string $allow_province
 * @property string $allow_city
 * @property integer $allow_sex
 * @property integer $allow_avart
 * @property string $first_time_follow_msg
 * @property string $level_one_msg
 * @property string $level_two_msg
 * @property string $repeat_scan_msg
 * @property integer $status
 * @property integer $area_msg
 * @property integer $sex_msg
 * @property integer $avart_msg
 * @property integer $date_msg
 */
class ActivityModel extends ActivityBase
{
    const TYPE_JI_FEN = 1;
    const TYPE_HONG_BAO = 2;
    const TYPE_KA_QUA = 3;

    const ALLOW_SEX_MAN = 1;
    const ALLOW_SEX_WOMAN = 2;
    const ALLOW_SEX_BOTH = 0;
    const ALLOW_SEX_ALL = 4;

    const ALLOW_AVART_YES = 1;
    const ALLOW_AVART_NO = 2;
    const ALLOW_AVART_ALL = 3;

    public static $award = [
        self::TYPE_JI_FEN => 'scores',
        self::TYPE_HONG_BAO => 'hb',
        self::TYPE_KA_QUA => 'kq',
    ];
    public static $awardTypeLabels = [
        self::TYPE_JI_FEN => '积分',
        self::TYPE_HONG_BAO => '红包',
        self::TYPE_KA_QUA => '卡券',
    ];


    public $_validate = [
        ['name', 'require', '活动名称必填'],
        ['app_id', 'require', 'app id必填'],
        ['app_secret', 'require', 'app secret必填'],
        ['guide', 'require', '引导关注素材链接必填'],
        ['award_type', 'require', '奖励类型必选'],
        ['award_first_min', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
        ['award_first_max', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
        ['award_one_min', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
        ['award_one_max', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
        ['award_two_min', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
        ['award_two_max', 'is_numeric', '活动奖励必须是数字', Model::MUST_VALIDATE, 'function'],
    ];

    /**
     * @param $data
     * 更改时间格式类型为时间戳
     */
    public function unix($data)
    {
        $this->start_date = strtotime($data['start_date']);
        $this->end_date = strtotime($data['end_date']);
    }

    /**
     * @param $id
     * @return bool
     * 修改单个判断以及create()验证
     */
    public function updateOne($id)
    {
        if (is_numeric($id) && !empty($id)) {
            $model = $this->find($id);
            if ($model) {
                if ($this->create()) {
                    if ($_FILES['backgroud_path']['name']) {
                        $upload = new UploadFile();// 实例化上传类
                        $upload->maxSize = 3145728;// 设置附件上传大小
                        $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                        $upload->saveRule = 'uniqid';

                        $subPath = 'public/upload/images/' . date('Ym') . '/' . date('d') . '/';
                        $imageRoot = RES_ROOT . $subPath;
                        mkdir($imageRoot, 0777, true);

                        $upload->savePath = $imageRoot; // 设置附件上传（子）目录
                        // 上传文件
                        $upload->upload();
                        $info = $upload->getUploadFileInfo();
                        $this->backgroud_path = $subPath . $info[0]['savename'];
                    }
                    $this->save();
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 用户是否满足活动
     * @param $user
     * @return bool
     */
    public function isAllow($user)
    {

        if (!$this->isFirstTimeFollow($user)) {
            $this->error = '已经关注过微信公众号';
            return false;
        }

        if (!$this->isFollowFromActivity($user)) {
            $this->error = '用户未参与海报推广活动';
            return false;
        }

        if (!$this->validateActivityTime($user)) {
            $this->error = $this->date_msg;
            return false;
        }

        if (!$this->validateArea($user)) {
            $this->error = $this->area_msg;
            return false;
        }

        if (!$this->validateAvatar($user)) {
            $this->error = $this->avart_msg;
            return false;
        }

        if (!$this->validateSex($user)) {
            $this->error = $this->sex_msg;
            return false;
        }

        return true;
    }

    protected function isFirstTimeFollow($user)
    {
        return $user->follow_time <= 1;
    }

    protected function isFollowFromActivity($user)
    {
        return $user->activity_id != 0;
    }

    protected function validateActivityTime($user)
    {
        return $this->start_date <= $user->join_time && $user->join_time <= $this->end_date;
    }

    protected function validateArea($user)
    {
        if ($this->allow_province == '' && $this->allow_city == '') {
            return true;
        }

        if ($this->allow_city == '') {
            return $this->allow_province == $user->province;
        }



        return $this->allow_province == $user->province && $this->allow_city == $user->city;
    }

    protected function validateSex($user)
    {
        if ($this->allow_sex == self::ALLOW_SEX_MAN) {
            return $user->sex == self::ALLOW_SEX_MAN;
        }
        if ($this->allow_sex == self::ALLOW_SEX_WOMAN) {
            return $user->sex == self::ALLOW_SEX_WOMAN;
        }
        if ($this->allow_sex == self::ALLOW_SEX_BOTH) {
            return $user->sex != 0;
        }
        if ($this->allow_sex == self::ALLOW_SEX_ALL) {
            return true;
        }

        return false;
    }

    protected function validateAvatar($user)
    {
        if ($this->allow_avart == self::ALLOW_AVART_YES) {
            return $user->pic != '';
        }
        if ($this->allow_avart == self::ALLOW_AVART_NO) {
            return $user->pic == '';
        }
        return true;
    }

    public function autoReply($keywords)
    {
        $this->where(['auto_reply_keyword' => $keywords])->find();

        return $this->link;
    }

    /**
     * 发送活动奖励
     * @param $user JfUserModel
     * @return bool
     */
    public function sendAward($user)
    {
        $app = WeChatApp::instance();

        if (!$this->isAllow($user)) {
            $app->sendCustomMessage([
                'touser' => $user->openid,
                'msgtype' => 'text',
                'text' => [
                    'content' => $this->error,
                ]
            ]);
            return false;
        }
        $col = static::$award[$this->award_type];
        $awardTypeLabel = static::$awardTypeLabels[$this->award_type];
        $number = $this->getFirstTimeFollowAward();
        $user->addAward($this->award_type, $number);

        /** @var JfUserModel $parent */
        $parent = new JfUserModel();
        $parent->find($user->parent_id);
        $app->sendCustomMessage([
            'touser' => $user->openid,
            'msgtype' => 'text',
            'text' => [
                'content' => strtr($this->first_time_follow_msg, [
                    '#昵称#' => $user->username,
                    '#上级#' => $parent->username,
                    '#积分#' => $number,
                    '#奖励类型#' => $awardTypeLabel,
                ]),
            ]
        ]);

        $number = $this->getParentAward();
        $parent->addAward($this->award_type, $number, $user->id);
        $app->sendCustomMessage([
            'touser' => $parent->openid,
            'msgtype' => 'text',
            'text' => [
                'content' => strtr($this->level_one_msg, [
                    '#昵称#' => $user->username,
                    '#积分#' => $number,
                    '#总分#' => $this->parseTotal($parent->$col),
                    '#奖励类型#' => $awardTypeLabel,
                ]),
            ]
        ]);

        /** @var JfUserModel $grandParent */
        $grandParent = new JfUserModel();
        if ($parent->parent_id) {
            $grandParent->find($parent->parent_id);
            $number = $this->getGrandParentAward();
            $grandParent->addAward($this->award_type, $number, $parent->id);
            $app->sendCustomMessage([
                'touser' => $grandParent->openid,
                'msgtype' => 'text',
                'text' => [
                    'content' => strtr($this->level_two_msg, [
                        '#下级#' => $parent->username,
                        '#昵称#' => $user->username,
                        '#积分#' => $number,
                        '#总分#' => $this->parseTotal($grandParent->$col),
                        '#奖励类型#' => $awardTypeLabel,
                    ]),
                ]
            ]);
        }

    }

    public function parseTotal($number)
    {
        if ($this->award_type != static::TYPE_HONG_BAO) {
            $number = (integer)$number;
        }

        return $number;
    }

    public function getFirstTimeFollowAward()
    {
        if ($this->award_type == static::TYPE_HONG_BAO) {
            $number = mt_rand($this->award_first_min * 100, $this->award_first_max * 100) / 100;
        } else {
            $number = mt_rand($this->award_first_min, $this->award_first_max);
        }

        return $number;
    }

    public function getParentAward()
    {
        if ($this->award_type == static::TYPE_HONG_BAO) {
            $number = mt_rand($this->award_one_min * 100, $this->award_one_max * 100) / 100;
        } else {
            $number = mt_rand($this->award_one_min, $this->award_one_max);
        }

        return $number;
    }

    public function getGrandParentAward()
    {
        if ($this->award_type == static::TYPE_HONG_BAO) {
            $number = mt_rand($this->award_two_min * 100, $this->award_two_max * 100) / 100;
        } else {
            $number = mt_rand($this->award_two_min, $this->award_two_max);
        }

        return $number;
    }

    private $_watermarks = '';

    /**
     * @return mixed
     */
    public function getWatermarks()
    {
        if (!$this->_watermarks) {
            $this->_watermarks = json_decode($this->poster_params) ?: '';
        }
        return $this->_watermarks;
    }

    /**
     * @param mixed $watermarks
     */
    public function setWatermarks($watermarks)
    {
        if ($watermarks) {
            $this->poster_params = json_encode($watermarks);
        }
        $this->_watermarks = $watermarks;
    }

    public function fields()
    {
        $a = parent::fields() ?: array();
        $array = array_merge($a, array('watermarks', 'poster_background'));

        return $array;
    }

    protected $_poster_background = '';

    /**
     * @return string
     */
    public function getPosterBackground()
    {
        if (!$this->_poster_background && $this->backgroud_path) {
            $this->_poster_background = PIC_ROOT . $this->backgroud_path;
        }
        return $this->_poster_background;
    }


}

?>